<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addRolesDialogBox = true"
        >添加角色</el-button
      >
      <el-table
        :data="rulesData"
        border
        style="width: 100%; min-width: 1084px;"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row
              v-for="item1 in props.row.children"
              :key="item1.id"
              class="centerRow"
              align="middle"
              type="flex"
              justify="center"
            >
              <el-col :span="5">
                <el-tag
                  color="#409eff"
                  effect="dark"
                  closable
                  @close="delRight(props.row.id, item1.id, props.row.children)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  class="centerRow"
                  align="middle"
                  type="flex"
                  justify="center"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      color="#67c23a"
                      effect="dark"
                      type="success"
                      @close="delRight(props.row.id, item2.id, item1.children)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      color="#e6a23c"
                      effect="dark"
                      @close="delRight(props.row.id, item3.id, item2.children)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" width="48"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRolesDialogVisible(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delRoles(row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="editRightsDialogVisible(row.id)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogBox"
      width="50%"
      @close="$refs.addRolesForm.resetFields()"
    >
      <el-form
        :model="addRolesForm"
        :rules="rules"
        ref="addRolesForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogBox = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogBox"
      width="50%"
      @close="$refs.editRolesForm.clearValidate()"
    >
      <el-form
        :model="editRolesForm"
        :rules="rules"
        ref="editRolesForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogBox = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="editRightsDialogBox" width="50%">
      <el-tree
        ref="tree"
        :data="rightsData"
        show-checkbox
        node-key="id"
        highlight-current
        :props="defaultProps"
        :default-expand-all="true"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRightsDialogBox = false">取 消</el-button>
        <el-button type="primary" @click="editRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      rulesData: [],
      rightsData: [],
      addRolesDialogBox: false,
      editRolesDialogBox: false,
      editRightsDialogBox: false,
      // 当前选中角色的id
      currentId: '',
      // 添加角色表单
      addRolesForm: {
        roleName: '',
        roleDesc: '',
      },
      // 修改角色表单
      editRolesForm: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      // 表单验证规则
      rules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '角色名称长度在2~8个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
      },

      // 树状表格配置
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
    };
  },
  methods: {
    // 删除角色指定权限
    delRight(roleId, rightId, item) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return this.__apis.rights.deleteRight(roleId, rightId);
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            const id = item.some((v, i) => {
              if (v.id === rightId) {
                return i;
              }
            });
            item.splice(id, 1);
            this.$message.success('取消权限成功');
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 获取树状权限列表选中项数组
    getLeafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafkeys(item, arr));
    },

    // 获取树状权限列表
    getRights(type) {
      this.__apis.rights.getRights(type).then((res) => {
        if (res.data.meta.status === 200) {
          this.rightsData = res.data.data;
        }
      });
    },
    // 获取当前树状权限选中项
    editRightsDialogVisible(id) {
      this.currentId = id;
      this.editRightsDialogBox = true;
      const newArr = [];
      this.$nextTick(function () {
        this.rulesData.forEach((v) => {
          if (v.id === id) {
            this.getLeafkeys(v, newArr);
            this.$refs.tree.setCheckedKeys(newArr);
          }

          // if (v.id === id) {
          //   v.children.forEach((v) => {
          //     v.children.forEach((v) => {
          //       v.children.forEach((v) => {
          //         newArr.push(v.id);
          //       });
          //     });
          //   });
          // }
        });

        // this.$refs.tree.setCheckedKeys(newArr);
      });
    },
    // 分配权限
    editRights(id) {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(',');
      this.__apis.rights
        .postRights({
          roleId: this.currentId,
          rids: idStr,
        })
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success('分配权限成功');
            // this.getRights('tree');
            this.getRoles();
            this.editRightsDialogBox = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 删除当前角色
    delRoles(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return this.__apis.roles.deleteRoles(id);
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success('删除成功');
            this.getRoles();
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 获取当前修改的角色信息，并且打开修改框
    editRolesDialogVisible(data) {
      this.editRolesDialogBox = true;
      this.editRolesForm.id = data.id;
      this.editRolesForm.roleName = data.roleName;
      this.editRolesForm.roleDesc = data.roleDesc;
    },
    // 修改角色
    editRoles() {
      this.$refs.editRolesForm
        .validate()
        .then(() => {
          return this.__apis.roles.editRoles(this.editRolesForm);
        })
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success('修改成功');
            this.getRoles();
            this.editRolesDialogBox = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesForm
        .validate()
        .then(() => {
          return this.__apis.roles.postRoles(this.addRolesForm);
        })
        .then((res) => {
          if (res.data.meta.status === 201) {
            this.$message.success('创建成功');
            this.getRoles();
            this.addRolesDialogBox = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 获取角色列表
    getRoles() {
      this.__apis.getRoles().then((res) => {
        // console.log(res);
        this.rulesData = res.data.data;
      });
    },
  },
  created() {
    this.getRoles();
    this.getRights('tree');
  },
};
</script>

<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.el-table__expanded-cell > .centerRow.el-row {
  border-top: 1px solid #efefef;
  border-right: 1px solid #efefef;
  border-left: 1px solid #efefef;
}
.el-table__expanded-cell > .centerRow.el-row:last-child {
  border-bottom: 1px solid #efefef;
}
.el-col.el-col-19 > .centerRow.el-row {
  border-left: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
.el-col.el-col-19 > .centerRow.el-row:last-child {
  border-bottom: 0;
}
.el-main {
  height: 100%;
}
.el-row {
  height: 100%;
}
.el-row .el-col.el-col-5,
.el-row .el-col.el-col-6 {
  text-align: center;
}
.outer {
  background-color: #dcdfe6;
  height: 100%;
  width: 100%;
}
.el-tag {
  margin: 10px 3px;
}
.el-table {
  margin-top: 15px;
}
.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 12px;
}
</style>
